﻿using System.Numerics;
using System.Text;
using LanqiQAwebapi.Interface;
using LanqiQAwebapi.Models;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;


namespace LanqiQAwebapi.Todo
{
    public class CacheService : ICacheService

    {
        private readonly IConnectionMultiplexer _cache;

        private readonly IDatabase _database;
        private readonly LanQiQaDBContext _LanQiQaDBContext;
        public CacheService(IConnectionMultiplexer cache, LanQiQaDBContext __LanQiQaDBContext)
        {
            _cache = cache;
            _LanQiQaDBContext = __LanQiQaDBContext;
            _database = _cache.GetDatabase();

        }
        public async Task AddBlackTokenAsync(string uid, string Token)
        {
            //AccessToken拉黑
            string AccessKey = uid + "_" + Token;
            await _database.StringSetAsync(AccessKey, Encoding.UTF8.GetBytes(Token), TimeSpan.FromDays(7));


            //RefishToken拉黑
            await _database.StringSetAsync(uid, Encoding.UTF8.GetBytes(Token), TimeSpan.FromDays(7));
        }


        /// <summary>
        /// 检查redis 是否存在拉黑token,True为拉黑
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        public async Task<bool> CheckTokenIsBlackeAsync(string uid)
        {
            var AccessKey = uid + "_" + "Token";
           // await RediskeyIsAsync(AccessKey, "Token", TimeSpan.FromHours(144));
            var data = await _database.StringGetAsync(AccessKey);
            if (data.ToString().Length > 0)
            {
                return false;
            }
            else
            {
                return true;

            }


        }
        /// <summary>
        /// 手机验证码缓存
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="MessageCode"></param>
        public async Task<bool> AddSendMessageAsync(string Phone, string MessageCode)
        {

            if (await IncrementAndCheckLimitAsync(Phone, 5))
            {
                string key = Phone + "_" +await GetSendMessageCount(Phone);

                 _database.StringSet(key, MessageCode, TimeSpan.FromMinutes(3));
                return true;
            }
            return false;

        }
        public async Task<string> GetPhoneMessageAsync(string phoneNumber, int count)
        {

            string key = phoneNumber + "_" + count.ToString();
           
            return  _database.StringGet(key);

        }
        private async Task<int> GetSendMessageCount(string phoneNumber)
        {
            string counterKey = $"daily_limit:verification_codes:{phoneNumber}";
            await RediskeyIsAsync(counterKey, "1");
            // 尝试获取当前计数
            RedisValue currentCount =await _database.StringGetAsync(counterKey);
            var count = int.Parse(currentCount.ToString());
            return count;
        }
        /// <summary>
        /// 每一次电话号码当前的一个计数,用户获取指定标识的电话号码code ，每天每个电话号码只能发送五次，每次时间时间间隔三分钟
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public async Task<int> PGetSendMessageCountAsync(string phoneNumber)
        {
            string counterKey = $"daily_limit:verification_codes:{phoneNumber}";
            // 尝试获取当前计数
            RedisValue currentCount = await _database.StringGetAsync(counterKey);
            var count = int.Parse(currentCount.ToString());
            return count;
        }
        public async Task<bool> IncrementAndCheckLimitAsync(string phoneNumber, int dailyLimit)
        {
            string counterKey = $"daily_limit:verification_codes:{phoneNumber}";
            // 尝试获取当前计数
            RedisValue currentCount = await _database.StringGetAsync(counterKey);
            // 如果计数不存在，将其设置为1，并设置过期时间为一天
            if (currentCount.IsNull)
            {
                await _database.StringSetAsync(counterKey, "1", TimeSpan.FromDays(1));
                return true;
            }
            // 将 RedisValue 转换为 long 类型
            long count = Convert.ToInt64(currentCount);
            // 如果计数存在，检查是否小于每日限制
            if (count < dailyLimit)
            {
                await _database.StringIncrementAsync(counterKey);
                return true;
            }
            return false;
        }
        public async Task GetHotquestionAsync(string Input)
        {


        }


        private async Task RediskeyIsAsync(string key, string value, TimeSpan? expiry)
        {
            if (!_database.KeyExists(key))
            {
                await _database.StringSetAsync(key, value, expiry);
            }
        }
        private async Task RediskeyIsAsync(string key, string value)
        {
            if (!_database.KeyExists(key))
            {
                await _database.StringSetAsync(key, value);
            }
        }
    }
}
